#! /usr/bin/env python
# coding=utf-8

# Create your views here.
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseBadRequest
from django.template import RequestContext
from django.contrib.sessions.models import Session
from models import *
import datetime, sys, settings, MySQLdb, re, threading, time, urllib, os, hashlib, cStringIO, Image, random, traceback
if '..' not in sys.path:
    sys.path.append('..')

from common.priviledge import *

def getCodeComponentMenuCommon(request):
    path = request.path
    if path != '/':
        path = PermissionFilter().dealPath(path)
        path += '?type=%s' % (request.GET['type'])

    request.menu = PermissionRepository().getFullMenu(path)

#@getMenu
def codeComponent(request):
    getCodeComponentMenuCommon(request)
    result = {}
    paramMap = {}
    pageObj = {}

    initParam(request, 'codeComponentFuncListForm', result, paramMap, pageObj)

    mongoDB = getThreadLocalMongoDB()['mongoDB']
    queryParam = {'type': int(request.GET['type'])}
    
    name = paramMap.get('name')
    if name:
        queryParam.update({'name': re.compile('(?i)^.*%s.*$' % (name))})

    items = [item for item in mongoDB.CodeComponent.find(queryParam).limit(pageObj['pageSize']).skip(pageObj['begin'])]
    totalResults = mongoDB.CodeComponent.find(queryParam).count()
    
    params = {
        'pageNo': pageObj['pageNo'],
        'pageSize': pageObj['pageSize'],
        'totalResults': totalResults,
        'items': items
        }

    result['page'] = getNormalPage(params)

    if request.GET.get('operate'):
        result['message'] = '操作成功!'

    return render_to_response('component/codeComponent.html', result, context_instance=RequestContext(request))

#@getMenuIfNotPost
def codeComponentCreate(request):
    if request.method == 'GET':
        getCodeComponentMenuCommon(request)
        result = {}
        mongoDB = getThreadLocalMongoDB()['mongoDB']
        result['tenLi'] = range(1,11)
        return render_to_response('component/codeComponentCreate.html', result, context_instance=RequestContext(request))
    
    mongoDB = getThreadLocalMongoDB()['mongoDB']
    id = getIncrementId('codeComponentId')
    codeComponent = {
        '_id': id,
        'id': id,
        'name': trim(request.POST['name']),
        'content': trim(request.POST['content']),
        'comment': trim(request.POST['comment']),
        'type': int(request.GET['type']),
        'createTime': getDateTimeYMDHMS(datetime.datetime.now()),
    }
    codeComponent['origLi'] = []
    for i in range(1,11):
        codeComponent['origLi'].append(request.POST['orig' + str(i)])
    mongoDB.CodeComponent.save(codeComponent)
    return HttpResponseRedirect('%s/%s?operate=True&type=%s&traceId=%s' % (request.basePath, 'component/codecomponent', request.GET['type'], request.traceId))

def codeComponentDelete(request):
    ids = request.POST.getlist('ids')
    ids = [int(item) for item in ids if re.match(r'^\d+$', item)]

    mongoDB = getThreadLocalMongoDB()['mongoDB']
    mongoDB.CodeComponent.remove({'_id': {'$in': ids}})

    return HttpResponseRedirect('%s/%s?operate=True&type=%s&traceId=%s' % (request.basePath, 'component/codecomponent', request.GET['type'], request.traceId))

#@getMenu
def codeComponentDigit(request, id):
    getCodeComponentMenuCommon(request)
    result = {}
    mongoDB = getThreadLocalMongoDB()['mongoDB']
    codeComponent = mongoDB.CodeComponent.find_one({'_id': int(id)})
    result['codeComponent'] = codeComponent

    if request.GET.get('operate'):
        result['message'] = '操作成功!'

    return render_to_response('component/codeComponentDigit.html', result, context_instance=RequestContext(request))

#@getMenuIfNotPost
def codeComponentDigitEdit(request, id):
    if request.method == 'GET':
        getCodeComponentMenuCommon(request)
        result = {}

        mongoDB = getThreadLocalMongoDB()['mongoDB']
        codeComponent = mongoDB.CodeComponent.find_one({'_id': int(id)})
        result['codeComponent'] = codeComponent
        result['tenLi'] = range(1,11)
        result['isEdit'] = 'True'

        return render_to_response('component/codeComponentCreate.html', result, context_instance=RequestContext(request))

    mongoDB = getThreadLocalMongoDB()['mongoDB']
    codeComponent = mongoDB.CodeComponent.find_one({'_id': int(id)})
    codeComponent['name'] = trim(request.POST['name'])
    codeComponent['content'] = trim(request.POST['content'])
    codeComponent['comment'] = trim(request.POST['comment'])
    codeComponent['origLi'] = []
    for i in range(1,11):
        codeComponent['origLi'].append(request.POST['orig' + str(i)])
    mongoDB.CodeComponent.save(codeComponent)

    return HttpResponseRedirect('%s/%s?operate=True&type=%s&traceId=%s' % (request.basePath, 'component/codecomponent/' + str(id), request.GET['type'], request.traceId))

def codeComponentDigitDelete(request, id):
    mongoDB = getThreadLocalMongoDB()['mongoDB']
    mongoDB.CodeComponent.remove({'_id': int(id)})
    return HttpResponseRedirect('%s/%s?operate=True&type=%s&traceId=%s' % (request.basePath, 'component/codecomponent/', request.GET['type'], request.traceId))

